<html>
<body>
	<h3>Sam's Calculator 60394890</h3>
	<h3>Type an expression in the following box</h3>
	<p>Type an expression in the following box (e.g., 10.5+20*3/25).</p>
	<ul>
		<li>Only numbers and +,-,* and / operators are allowed in the expression.</li>
	<li>The evaluation follows the standard operator precedence.</li>
	<li>The calculator does not support parentheses.</li>
	<li>The calculator handles invalid input "gracefully". It does not output PHP error messages.</li>
	
	</ul>
	<form action="calculator.php" method="GET">
		<input type="text" name="expression" />
		<input value="calculate" type="submit" />
	</form>
	<h3>Result</h3>
	<?php
		error_reporting(0);
		if($_GET['expression'])
		{
			$expression = $str=str_replace(" ","",trim($_GET['expression']));
			if(validate($expression))
			{
				echo $expression ." = " .evaluate($expression);
				
			}else
			{
				echo "Invalid input expression: ".$_GET['expression'];
			}
				
		}
	
	?>
	
</body>
</html>

<?php 
	function validate($expression){
		$rege="/^-?[0-9]*\.?[0-9]+((([*\/+]-)|[*\/+-])[0-9]*\.?[0-9]+)*$/";
		return preg_match( $rege, $expression,$match ) == 1 ;
		//print_r($match);
	
	}	
	function evaluate($expression){
		//check division by zero 
		//either ends with end of line or +-*/ -> either ([*\/+-].*)?$ or ([*\/+-]|\z)
		if(preg_match("/\/-?0*\.?0+([*\/+-].*)?$/",$expression,$match)==0)
		{
			eval("\$ans = $expression ;");
			return $ans;
		}else{
			//print_r($match);
			return "";
		}
	}


?>